<?php
/**
 * Created by PhpStorm.
 * User: Lzhy ysjywz@gmail.com
 * Date: 2019/9/11
 * Time: 1:35 PM
 */
namespace Core\common;

class Wechat
{
    use \Core\traits\Wechat;

    /**
     * 获取当前公众号accessToken
     * @return mixed
     */
    public static function assessToken()
    {
        try{
            $account_api = \WeAccount::create();
            $token = $account_api->getAccessToken();
            
            return $token;
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }

    /**
     * @param string $url
     * @return mixed
     */
    public static function getJsSdk($url = '')
    {
        try{
            $account_api = \WeAccount::create();
            $sdk = $account_api->getJssdkConfig($url);

            return $sdk;
        }catch (\Exception $e){
            exit($e->getMessage());
        }
    }

    /**
     * 微信网页授权
     * @param string $scope
     * @param bool $refresh
     * @return mixed
     */
    public static function oauth2($scope = 'userinfo',$refresh = false)
    {
        $code = I('code');
        $url  = Request::url();
        $appId  = Assist::globalVal('account.key');
        if(empty($code)){
            $openid = $_SESSION['__openid__'];
            if($openid && $refresh === false){
                $userInfo = self::getUserInfoByOpenid($openid);
                $_SESSION['__openid__'] = $userInfo['openid'];
                return $userInfo;
            }
            self::authRedirect($appId,$url,$scope);
        }
        $appSecret = Assist::globalVal('account.secret');
        $userInfo = self::oauth2UserInfo($appId,$appSecret,$code);
        $_SESSION['__openid__'] = $userInfo['openid'];

        return $userInfo;
    }
}